/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package im.node;

import im.general.AbstractListenBehaviour;
import im.general.Config;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author brownstone
 */
public class NotifyListenBehaviour extends AbstractListenBehaviour {
    MobileNodeAgent mobileNodeAgent;
    public NotifyListenBehaviour(MobileNodeAgent mobileNodeAgent) {
        this.mobileNodeAgent = mobileNodeAgent;
        mt = MessageTemplate.or(MessageTemplate.MatchEncoding("NN"), MessageTemplate.MatchPerformative(ACLMessage.SUBSCRIBE));
    }

    @Override
    protected void handleMessage(ACLMessage msg) {
        //msg.setEncoding(STATE_READY);
        //System.out.println(this.getClass().getName()+"notify message received");
        notifyRecipient(Config.EVENT_SERVICE_NAME, msg);
    }

    public void notifyRecipient(String coordinator, ACLMessage msg) {
        ACLMessage nmsg = new ACLMessage();
        nmsg.setEncoding(Config.NOTIFY_RECIPIENT);
        try {
            try {
                nmsg.setContentObject(msg.getContentObject());
            } catch (UnreadableException ex) {
                Logger.getLogger(NotifyListenBehaviour.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(NotifyListenBehaviour.class.getName()).log(Level.SEVERE, null, ex);
        }
        mobileNodeAgent.addReceiver(coordinator, nmsg);
        mobileNodeAgent.sendMessage(nmsg);
    }
}
